<template>
  <div class="map">
    <div id="cesiumContainer"></div>
  </div>
</template>

<script>
// 引入安定区边界数据和漫游路线数据
import andingqu from "@/js/andingqu.json";
// import manyou from "@/js/manyou.json";
// import line from "@/js/line.json";
import gsap from "gsap";
import Bus from "@/js/EventBus";
import {
  addWMSLayer,
  showOrhideWMSLayer,
  cameraFlyto,
  showOrhideBaseLayer,
} from "@/js/layer";
import { addLayer, showLayer, hideLayer } from "@/js/layer1";
import { basegeoserver } from "../../../public/mapconfig";
import {
  getpolyLineData,
  getpolyLineData1,
  getpolyPointData,
  getpolyxzqhData,
  getBoxPointData,
  getBoxLineData,
  getYXQYidData,
} from "@/api/http";
// 二维流向材质
// import "@/js/ImageLineMaterial";
// 三维自定义流向材质
import PolyLineTest from "@/js/PolylineTest";
// 挖方效果
import TerrainClipPlan from "@/js/TerrainClipPlan";
// 量算
import "@/js/cesium-measure.js";

import { TOKRN } from "../../../public/mapconfig";
export default {
  data() {
    return {
      viewer: null,
      primitiveList: [],
      labels: null,
      labelslist: [],
      addgxlx: false,
      addcunming: false,
      addcundian: false,
      addsltclayer: false,
      // 是否贴地
      clampToGround: true,
      // infowindow传出的数据（id）
      // infodata: null,
      // 所有管线高亮的数组
      heightColorlinesList: [],
      heightColorpointsList: null,
      heightColorpointsType: null,
      // 爆管分析暂存的数据
      bgfxData: [],
      // 缓冲区域的暂存数据
      allyxqudata: [],
      // 挖方暂存实体
      terrainClipPlan: null,
      // 飞行的服务
      dataSources: null,
      entityB2: null,
      onTickEvent: null,
      guanlineliuxadd: false,
      btntype: 2,
      guanxian: [],
    };
  },
  computed: {
    maptype() {
      return this.$store.getters.maptype;
    },
    famendata() {
      return this.$store.getters.famendata;
    },
    guanxiandata() {
      return this.$store.getters.guanxiandata;
    },
    xzqhlayerdata() {
      return this.$store.getters.xzqhlayerdata;
    },
    mapstatus() {
      return this.$store.getters.mapstatus;
    },
    mapinit() {
      return this.$store.getters.mapinit;
    },
    toolbarshowhide() {
      return this.$store.getters.toolbarshowhide;
    },
    manyoudata() {
      return this.$store.getters.manyoudata;
    },
    // btntype() {
    //   return this.$store.getters.btntype;
    // },
  },
  created() {
    this.$nextTick(() => {
      this.getData(this.updateMap);
      // this.getData1();
    });

    let btntype = window.sessionStorage.getItem("btntype");
    if (btntype) {
      this.btntype = btntype;
    }
  },
  beforeDestroy() {
    // 移除事件监听器
    // Bus.$off("btntype");
    Bus.$off("layer");
    // Bus.$off("Polyline");
    // Bus.$off("Polygon");
    // Bus.$off("Height");
    // Bus.$off("Clear");
    // Bus.$off("ZoomOut");
    // Bus.$off("GoHome");
    // Bus.$off("ZoomIn");
    // Bus.$off("draw");
    // Bus.$off("initlineandpoint");
    // Bus.$off("gffx");
    // Bus.$off("ltfx");
    // Bus.$off("bgfx");
    // Bus.$off("removedraw");
    // Bus.$off("startFly2");
    // Bus.$off("exitFly2");
    // Bus.$off("addpoint");
    // Bus.$off("removepoint");
    // Bus.$off("addlinecolor");
    // Bus.$off("removealllinecolor");
    // Bus.$off("removelinecolor");
    // Bus.$off("dingwei");
    // Bus.$off("selectyxqu");
    // Bus.$off("removeyxqu");
    // Bus.$off("xiaohui");
  },
  mounted() {
    this.initMap();
    Bus.$on("btntype", (e) => {
      this.btntype = e;
    });
    Bus.$on("layer", (e) => {
      // console.log("layer选中传过来的数据2d", e);
      if (e[0] == null) {
        return;
      }
      this.addImagelayer(e[0], e[1]);
    });
    Bus.$on("Polyline", (e, r) => {
      // console.log(e);
      this.measureDestroy();
      this.measurePolyLine(e, r);
    });
    Bus.$on("Polygon", (e, r) => {
      this.measureDestroy();
      this.measurePolygon(e, r);
    });
    Bus.$on("Height", (e) => {
      this.measureDestroy();
      this.measureHeight();
    });
    Bus.$on("Clear", (e) => {
      this.measureDestroy();
    });
    Bus.$on("ZoomOut", (e) => {
      // console.log(e);
      this.zoomout(e);
    });
    Bus.$on("GoHome", (e) => {
      // console.log(e);
      this.gohome(e);
    });
    Bus.$on("ZoomIn", (e) => {
      // console.log(e);
      this.zoomin(e);
    });
    Bus.$on("draw", (e) => {
      // console.log(e);
      // this.zoomin(e);
      this.drawPolygon(e);
    });
    // 重置-初始化
    Bus.$on("initlineandpoint", (e) => {
      this.clearHeightColoridlist();
      this.removenewpoint();
      this.removeallyxqu();
      this.removePolygon();
      Bus.$emit("gffx", false);
      Bus.$emit("ltfx", false);
      Bus.$emit("bgfx", false);
      this.measureDestroy();
    });

    Bus.$on("removedraw", (e) => {
      this.removePolygon();
      // console.log(e);
      // this.zoomin(e);
      // this.drawPolygon(e)
    });

    Bus.$on("bgfx", (e) => {
      this.bgfx = e;
      if (e == false) {
        this.bgfxData = [];
        this.removematerialREDline();
        this.clearHeightColoridlist();
        this.removenewpoint();
      }
    });
    Bus.$on("ltfx", (e) => {
      this.ltfx = e;
      if (e == false) {
        this.clearHeightColoridlist();
        // this.clearHeightColor(this.heightColorlinesList);
      }
    });
    Bus.$on("gffx", (e, data) => {
      if (e == false) {
        this.clearHeightColoridlist();
        // this.clearpointHeightColoridlist();
        this.removenewpoint();
      } else {
      }
    });
    // Bus.$on("kwfx", (e, data) => {
    //   if (e == false) {
    //     this.clearExcavation();
    //   } else {
    //     this.excavationAnalysis(data);
    //   }
    // });

    // Bus.$on("startFly2", (e) => {
    //   this.startFly(e);
    // });
    // Bus.$on("exitFly2", (e) => {
    //   this.exitFly();
    // });
    //  添加高亮图标
    Bus.$on("addpoint", (e) => {
      this.removenewpoint();
      this.addnewpoint(e);
    });
    //  清楚高亮图标
    Bus.$on("removepoint", (e) => {
      this.removenewpoint();
      // this.addnewpoint(e)
    });
    // 添加高亮管线
    Bus.$on("addlinecolor", (e) => {
      this.addlinesHeightColor(e);
    });
    // 清楚s所有高亮管线
    Bus.$on("removealllinecolor", (e) => {
      this.clearHeightColoridlist();
    });
    // 清楚单个高亮管线
    Bus.$on("removelinecolor", (e) => {
      let newlist = [];
      // console.log(this.heightColorlinesList, "this.heightColorlinesList");
      this.heightColorlinesList.forEach((element) => {
        if (e == element.properties.UserID) {
          newlist.push(element);
        }
      });
      this.clearHeightColor(newlist);
    });
    Bus.$on("dingwei", (e) => {
      this.dingweiFly(e);
    });
    Bus.$on("selectyxqu", (e) => {
      this.selectallyxqu1(e);
    });
    // Bus.$on("selectyxqu1", (e) => {
    //   this.selectallyxqu1(e);
    // });
    Bus.$on("removeyxqu", (e) => {
      this.removeallyxqu();
    });
    Bus.$on("xiaohui", (e) => {
      this.viewer.destroy();
    });
  },
  methods: {
    // 初始化地图
    initMap() {
      Cesium.Ion.defaultAccessToken =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxNmEzOGY5YS1jOGQ0LTQ0YWUtYjc5Zi1iNWNiNDQyMzliZTYiLCJpZCI6MzczOTQsImlhdCI6MTcwNTkwODA4MH0.Zcwa37fVh1PbYNzH-4LCNQBkr-XeBjUVk88fPmtIf-s";
      const viewer = (this.viewer = new Cesium.Viewer("cesiumContainer", {
        sceneMode: Cesium.SceneMode.SCENE3D,
        // terrainProvider: Cesium.createWorldTerrain(),
        vrButton: false,
        animation: false,
        baseLayerPicker: false,
        geocoder: false,
        timeline: false,
        fullscreenButton: false,
        homeButton: false,
        // creditContainer: document.createElement("div"),
        infoBox: false,
        navigationHelpButton: false,
        sceneModePicker: false,
        scene3DOnly: false,
        shouldAnimate: true, //开启动画
        selectionIndicator: false,
      }));
      viewer.scene.globe.depthTestAgainstTerrain = false;
      viewer.cesiumWidget.creditContainer.style.display = "none";
      viewer.scene.screenSpaceCameraController.maximumZoomDistance = 600000;
      // console.log(window.Cesium.viewer, "window");
      //   this.viewer = viewer;
      this.gohome(3);
      this.addYanmo(viewer);
      this.addbaselayers(viewer);
      //   添加掩膜
    },
    // 添加地图上的覆盖物
    updateMap() {
      Bus.$emit("initlayers", true);
      let viewer = this.viewer;
      this.addAllLine(this.initlayers);
      this.addAllPoint();
      this.addAllLabel();
      this.addMouseclickandhover();
      this.addxzqhlayer();
    },
    // async getData1() {
    //   getpolyLineData1()
    //     .then((res) => {
    //       // console.log(res);
    //       if (res) {
    //         if (res.features.length == res.totalFeatures) {
    //           // this.addpolylineColume(viewer, res);
    //           this.guanxian.push(res.features)
    //           // console.log(this.guanxian.flat())
    //           this.$store.commit("changeguanxiandata", this.guanxian.flat());
    //           res.features.forEach((element) => {
    //             this.Thematiclayer.forEach((e) => {
    //               if (e.grade == element.properties.grade) {
    //                 e.data.push(element);
    //               }
    //             });
    //           });
    //           //
    //         }
    //       }
    //     })
    //     .catch((err) => {
    //       console.log(err);
    //     });
    // },
    // 分组处理管线和阀门的数据
    // 获取所有数据
    async getData(callback) {
      // console.log(this.Thematiclayer, "Thematiclayer22222222222");
      this.Thematiclayer.forEach((element) => {
        if (element.type == "line" || element.type == "point") {
          element.data = [];
          element.load = false;
        }
      });
      const res = await getpolyLineData();
      // const res = line;
      // console.log("================1===========");
      if (res) {
        if (res.features.length == res.totalFeatures) {
          // this.addpolylineColume(viewer, res);
          // this.$store.commit("changeguanxiandata", res);
          this.guanxian.push(res.features);
          res.features.forEach((element) => {
            this.Thematiclayer.forEach((e) => {
              if (e.grade == element.properties.grade) {
                e.data.push(element);
              }
            });
          });
          //
        }
      }
      // console.log(this.Thematiclayer);

      const res1 = await getpolyPointData();
      // console.log(res1, "================2===========");
      if (res1) {
        if (res1.features.length == res1.totalFeatures) {
          // this.addbillboardCollection(viewer, res1);

          let data = {
            features: [],
          };

          res1.features.forEach((element) => {
            if (element.properties.sttp != "" && element.properties.device_id != "") {
              data.features.push(element);
            }
          });
          // console.log(arr1, arr2, "数据")
          this.$store.commit("changefamendata", data);
          // let param=true
          // this.addAllPointEntity(data.features, function () {
          //   // alert("这是回调" + arg1 + " " + arg2);
          //   Bus.$emit("initlayers", true);
          // });

          // this.addAllPointEntity(data.features , function (params))

          data.features.forEach((element) => {
            this.Thematiclayer.forEach((e) => {
              if (e.sttp == element.properties.sttp) {
                e.data.push(element);
              }
            });
          });
        }
      }
      // console.log(this.Thematiclayer, "Thematiclayer");
      const res3 = await getpolyxzqhData();
      // console.log(res3, "================3===========");
      this.$store.commit("changexzqhlayerdata", res3.features);

      console.log(this.Thematiclayer, "Thematiclayer_2d数据获取");
      // debugger;
      // window.sessionStorage.setItem("token", "/cesium2d");
      callback();
    },
    // 添加所有管线（true为需要显示的）
    addAllLine(callback) {
      this.Thematiclayer.forEach((element) => {
        if (element.type == "line" && element.show == true) {
          this.addOnceLineEntity(element);
        }
      });

      callback();
    },
    // 添加所有管点（true为需要显示的）
    addAllPoint() {
      var dataSource1 = new Cesium.CustomDataSource("dataSource1");
      let that = this;
      this.Thematiclayer.forEach((element) => {
        if (element.type == "point" && element.show == true) {
          var showrgb = true;
          // if (element.show == true) {
          //   showrgb = true;
          // } else {
          //   showrgb = false;
          // }
          // console.log(element);
          element.data.forEach((e) => {
            // console.log("deviceId", e.id);
            let imgtype = e.properties.sttp;
            var img;
            switch (imgtype) {
              case "0":
                // 管道分界监控点
                img = require("@/assets/poi/fjjcd.png");
                break;
              case "1":
                // 管道非分界监控点
                img = require("@/assets/poi/ffjjcd.png");
                break;
              case "2":
                // 蓄水池测控点
                img = require("@/assets/poi/xscjcd.png");
                break;
              case "3":
                // 泵站测控点
                img = require("@/assets/poi/bzjcd.png");
                break;
              case "4":
                img = require("@/assets/poi/sc.png");
                break;
              case "5":
                img = require("@/assets/poi/sfz.png");
                break;
            }
            let idData = {
              deviceId: e.properties.device_id,
              // jctype: e.properties.type,
              // sttp: e.properties.sttp,
            };
            dataSource1.entities.add(
              new Cesium.Entity({
                id: JSON.stringify(idData),
                position: Cesium.Cartesian3.fromDegrees(
                  e.geometry.coordinates[0],
                  e.geometry.coordinates[1],
                  4
                ),
                show: showrgb,
                billboard: {
                  pixelOffset: new Cesium.Cartesian2(0, -19),
                  image: img,
                  width: 34,
                  height: 38,

                  //  heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                  disableDepthTestDistance: 200000,
                },
              })
            );
          });
        }
      });
      dataSource1.id = "dataSource1";
      var dataSourcePromise = this.viewer.dataSources.add(dataSource1);
      dataSourcePromise.then(function (dataSource) {
        // console.log(dataSource,"dataSource")
        const pixelRange = 50;
        const minimumClusterSize = 2;
        const enabled = true;

        dataSource.clustering.enabled = enabled; //聚合开启
        dataSource.clustering.pixelRange = pixelRange; //设置像素范围，以扩展显示边框
        dataSource.clustering.minimumClusterSize = minimumClusterSize; //设置最小的聚合点数目，超过此数目才能聚合

        let removeListener;
        function combineIconAndLabel(url, label, size) {
          // 创建画布对象
          let canvas = document.createElement("canvas");
          canvas.width = size;
          canvas.height = size;
          let ctx = canvas.getContext("2d");

          let promise = new Cesium.Resource.fetchImage(url).then((image) => {
            // 异常判断
            try {
              ctx.drawImage(image, 0, 0);
            } catch (e) {
              // console.log(e);
            }

            // 渲染字体
            // font属性设置顺序：font-style, font-variant, font-weight, font-size, line-height, font-family
            ctx.fillStyle = Cesium.Color.WHITE.toCssColorString();
            ctx.font = "bold 18px Microsoft YaHei";
            ctx.textAlign = "center";
            ctx.textBaseline = "middle";
            ctx.fillText(label, size / 2, size / 2);

            return canvas;
          });
          return promise;
        }

        customStyle();

        function customStyle() {
          if (Cesium.defined(removeListener)) {
            removeListener();
            removeListener = undefined;
          } else {
            removeListener = dataSource.clustering.clusterEvent.addEventListener(
              function (clusteredEntities, cluster) {
                cluster.label.show = false;
                cluster.billboard.show = true;
                cluster.billboard.id = cluster.label.id;
                cluster.billboard.verticalOrigin = Cesium.VerticalOrigin.BOTTOM;

                if (clusteredEntities.length >= 40) {
                  // cluster.billboard.image = combineIconAndLabel(require('@/assets/poi/gz.png'), clusteredEntities.length, 255);
                  cluster.billboard.image = combineIconAndLabel(
                    "https://a.amap.com/jsapi_demos/static/images/red.png",
                    clusteredEntities.length,
                    48
                  );

                  cluster.billboard.width = 35;
                  cluster.billboard.height = 35;
                } else if (clusteredEntities.length >= 30) {
                  cluster.billboard.image = combineIconAndLabel(
                    "https://a.amap.com/jsapi_demos/static/images/red.png",
                    clusteredEntities.length,
                    48
                  );
                  cluster.billboard.width = 35;
                  cluster.billboard.height = 35;
                } else if (clusteredEntities.length >= 20) {
                  cluster.billboard.image = combineIconAndLabel(
                    "https://a.amap.com/jsapi_demos/static/images/orange.png",
                    clusteredEntities.length,
                    36
                  );
                  cluster.billboard.width = 35;
                  cluster.billboard.height = 35;
                } else if (clusteredEntities.length >= 10) {
                  cluster.billboard.image = combineIconAndLabel(
                    "https://a.amap.com/jsapi_demos/static/images/green.png",
                    clusteredEntities.length,
                    32
                  );
                  cluster.billboard.width = 35;
                  cluster.billboard.height = 35;
                } else {
                  cluster.billboard.image = combineIconAndLabel(
                    "https://a.amap.com/jsapi_demos/static/images/blue.png",
                    clusteredEntities.length,
                    32
                  );
                  cluster.billboard.width = 35;
                  cluster.billboard.height = 35;
                }
              }
            );
          }
        }
      });
    },
    // 添加所有管线的文字显示（true为需要显示的）
    addAllLabel() {
      this.Thematiclayer.forEach((element) => {
        if (element.type == "line" && element.show == true) {
          this.addOnceLabelEntity(element);
        }
      });
      // this.labelslist.push(labels) ;
    },
    // 重置图层的显示（管线和管点不做重置）
    initlayers() {
      this.Thematiclayer.forEach((element) => {
        if (element.type == "entity" || element.type == "geoserver") {
          if (element.layername == "ANDINGQU:xzqhlayer") {
            element.show = true;
          } else {
            element.show = false;
          }
        }
      });

      // console.log("xian  加载完毕1111111111111111111")
    },
    // 添加掩膜
    addYanmo(viewer) {
      let response = andingqu;
      // console.log(andingqu, "andingqu");
      var maskspoint = Cesium.Cartesian3.fromDegreesArray(
        response.features[0].geometry.coordinates[0].flat()
      );
      const entity1 = new Cesium.Entity({
        id: 1,
        polygon: {
          clampToGround: true,
          hierarchy: {
            // 绘制的区域太大容易卡顿
            positions: [
              {
                x: 3197104.586923899,
                y: 0.5580000157243585,
                z: 5500477.1339386385,
              },
              {
                x: 3197104.586923899,
                y: 0.5580000157243585,
                z: -5500477.1339386385,
              },
              {
                x: -3197104.5869239476,
                y: 3.915323898915733,
                z: -5500477.1339386385,
              },
              {
                x: -3197104.5869239476,
                y: 3.915323898915733,
                z: 5500477.1339386385,
              },
              {
                x: 3197104.586923899,
                y: 0.5580000157243585,
                z: 5500477.1339386385,
              },
            ],
            // holes是图形内需要挖空的区域
            holes: [
              {
                positions: maskspoint,
              },
            ],
          },
          material: Cesium.Color.fromCssColorString("#0C1F34").withAlpha(0.8),
          // material: Cesium.Color.WHITE.withAlpha(1),
        },
      });
      viewer.entities.add(entity1);
      // viewer.entities.add({
      //   polygon: {
      //     // 获取指定属性（positions，holes（图形内需要挖空的区域））
      //     hierarchy: {
      //       //左下左上右上右下
      //       // 0,60,0,-60,180,-60,180,60,0,-60
      //       positions: [
      //         {
      //           x: 3197104.586923899,
      //           y: -0.5580000157243585,
      //           z: 5500477.1339386385,
      //         },
      //         {
      //           x: 3197104.586923899,
      //           y: -0.5580000157243585,
      //           z: -5500477.1339386385,
      //         },
      //         {
      //           x: -3197104.5869239476,
      //           y: -3.915323898915733,
      //           z: -5500477.1339386385,
      //         },
      //         {
      //           x: -3197104.5869239476,
      //           y: -3.915323898915733,
      //           z: 5500477.1339386385,
      //         },
      //         {
      //           x: 3197104.586923899,
      //           y: -0.5580000157243585,
      //           z: 5500477.1339386385,
      //         },
      //       ],
      //     },
      //     // 边框
      //     outline: false,
      //     // 边框颜色
      //     outlineColor: Cesium.Color.WHITE,
      //     // 边框尺寸
      //     outlineWidth: 2,
      //     // 填充的颜色，withAlpha透明度
      //     // material: Cesium.Color.BLUE.withAlpha(0.5),
      //     material: Cesium.Color.fromCssColorString("#0C1F34").withAlpha(0.8),
      //     // 是否被提供的材质填充
      //     fill: true,
      //     // 是否显示
      //     show: true,
      //     // 顺序,仅当`clampToGround`为true并且支持地形上的折线时才有效。
      //     zIndex: 10,
      //   },
      // });
      // viewer.entities.add({
      // 			polygon: {
      // 				// 获取指定属性（positions，holes（图形内需要挖空的区域））
      // 				hierarchy: {
      // 					//左下左上右上右下
      // 					// 0,60,0,-60,180,-60,180,60,0,-60
      // 					positions: [{
      // 						x: 3197104.586923899,
      // 						y: 0.5580000157243585,
      // 						z: 5500477.1339386385
      // 					}, {
      // 						x: 3197104.586923899,
      // 						y: 0.5580000157243585,
      // 						z: -5500477.1339386385
      // 					}, {
      // 						x: -3197104.5869239476,
      // 						y: 3.915323898915733,
      // 						z: -5500477.1339386385
      // 					}, {
      // 						x: -3197104.5869239476,
      // 						y: 3.915323898915733,
      // 						z: 5500477.1339386385
      // 					}, {
      // 						x: 3197104.586923899,
      // 						y: 0.5580000157243585,
      // 						z: 5500477.1339386385
      // 					}],
      // 				},
      // 				// 边框
      // 				outline: false,
      // 				// 边框颜色
      // 				outlineColor: Cesium.Color.RED,
      // 				// 边框尺寸
      // 				outlineWidth: 200,
      // 				// 填充的颜色，withAlpha透明度
      // 				material: Cesium.Color.BLUE.withAlpha(0.5),
      // 				// 是否被提供的材质填充
      // 				fill: true,
      // 				// 是否显示
      // 				show: true,
      // 				// 顺序,仅当`clampToGround`为true并且支持地形上的折线时才有效。
      // 				zIndex: 10
      // 			}
      // 		});
    },
    // 添加基础底图（矢量图，矢量标注）
    addbaselayers(viewer) {
      //在线天地图矢量地图服务(墨卡托投影)
      // let token = "1e2e780493e477fb45f55694cae76a5a";
      let token = TOKRN;
      // console.log(token, "token");
      var TDT_VEC_W =
        "http://t0.tianditu.com/vec_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=vec&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&" +
        `tk=${token}`;
      var TDT_CVA_W =
        "http://t0.tianditu.com/cva_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cva&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&" +
        `tk=${token}`;
      // console.log("1111111111")
      addLayer(viewer, "WMTS", "矢量图层", "ANDINGQU:sltclayer", TDT_VEC_W, {
        hue: 3,
        contrast: -1.2,
        show: false,
      });
      addLayer(viewer, "WMTS", "矢量文字标注", "tdtBasicLayer2", TDT_CVA_W);

      // console.log("222222222")

      // var baselayer = viewer.imageryLayers.addImageryProvider(
      //   new Cesium.WebMapTileServiceImageryProvider({
      //     url: TDT_VEC_W,
      //     layer: "ANDINGQU:sltclayer",
      //     style: "default",
      //     format: "image/jpeg",
      //     tileMatrixSetID: "GoogleMapsCompatible",
      //   })
      // );
      // viewer.imageryLayers.addImageryProvider(
      //   new Cesium.WebMapTileServiceImageryProvider({
      //     //调用影响中文注记服务

      //     url: TDT_CVA_W,
      //     layer: "tdtBasicLayer2",
      //     style: "default",
      //     format: "image/jpeg",
      //     tileMatrixSetID: "GoogleMapsCompatible",
      //   })
      // );
      // this.baselayer = baselayer;

      // 更改地图样式   色调    对比度
      // layerOption
      // baselayer.hue = 3;
      // baselayer.contrast = -1.2;
      // baselayer.show = false;
      // baselayer.id = "sltclayer";

      // console.log(viewer.imageryLayers._layers);
      // this.addlayers(viewer);
    },
    // 获取图层列表点击选中的图层和状态
    addImagelayer(data, type) {
      switch (type) {
        case true:
          this.Thematiclayer.forEach((element) => {
            if (element.layername == data.layername) {
              // console.log(element.layername, "true");
              this.addImagelayerEntity(element);
            }
          });

          break;
        case false:
          this.Thematiclayer.forEach((element) => {
            if (element.layername == data.layername) {
              // console.log(element.layername, "false")
              this.removeImagelayerEntity(element);
            }
          });

          break;

        default:
          break;
      }
    },
    // 区分显示对应的图层
    addImagelayerEntity(res) {
      // console.log(res);
      switch (res.type) {
        case "line":
          this.addLineEntity(res);
          this.addLabelEntity(res);
          this.showLayerliuxiang(res);

          break;
        case "point":
          this.addPointEntity(res.data);
          break;
        case "entity":
          this.addentity(res.layername);
          break;
        case "geoserver":
          this.addgeoserver(res.layername);
          break;

        default:
          break;
      }
    },
    //区分隐藏对应的图层
    removeImagelayerEntity(res) {
      // console.log(res);

      switch (res.type) {
        case "line":
          this.removeLineEntity(res);
          this.removeLabelEntity(res);
          this.hideLayerliuxiang(res);

          break;
        case "point":
          this.removePointEntity(res.data);
          break;
        case "entity":
          this.removeentity(res.layername);
          break;
        case "geoserver":
          this.removegeoserver(res.layername);
          break;
        default:
          break;
      }
    },
    // 第一次选择管线图层（添加）
    addOnceLineEntity(res) {
      // console.log(res);
      // console.log("第一次加载");
      var instances = [];

      this.Thematiclayer.forEach((element) => {
        if (element.id == res.id) {
          element.load = true;
          var showrgb = 255;
          element.data.forEach((e) => {
            if (e.geometry.coordinates[0][0].length == 2) {
              e.geometry.coordinates[0].forEach((item) => {
                // element.push( Math.round(Math.random()*100+1500));
                // item.push(0.1);
              });
            }
            // console.log(e.geometry.coordinates[0].flat());
            let colortype = e.properties.grade;
            var color;
            switch (colortype) {
              case "0":
                // 输水干管
                // color = "#00a9fd";
                color = [255, 122, 0];

                break;
              case "1":
                // 供水干管
                // color = "#6fe1f9";
                color = [0, 169, 253];

                break;
              case "2":
                // 分支管
                // color = "#ff7a00";
                color = [111, 225, 249];

                break;
              case "3":
                // 直分支管
                // color = "#fda75d";
                color = [111, 225, 249];

                break;
              case "4":
                // 支管
                // color = "#44ab4f";
                color = [68, 171, 79];

                break;
              case "5":
                // 分支管
                // color = "#80b4eb";
                color = [128, 180, 235];

                break;
            }
            let idData = {
              UserID: e.properties.UserID,
            };
            let pos = e.geometry.coordinates[0].flat();
            instances.push(
              new Cesium.GeometryInstance({
                geometry: new Cesium.GroundPolylineGeometry({
                  positions: Cesium.Cartesian3.fromDegreesArray(pos),
                  width: 4,
                  zIndex: 1,
                  // width: 10
                }),

                id: JSON.stringify(idData),
                attributes: {
                  color: Cesium.ColorGeometryInstanceAttribute.fromColor(
                    new Cesium.Color.fromBytes(color[0], color[1], color[2], showrgb)
                  ),
                },
              })
            );
          });
        }
      });
      var primitive = new Cesium.GroundPolylinePrimitive({
        geometryInstances: instances,
        appearance: new Cesium.PolylineColorAppearance(),
      });
      // this.viewer.scene.groundPrimitives._zIndex=0
      var lines = this.viewer.scene.groundPrimitives.add(primitive);
      lines.id = res.id;
      lines.type = "line";
      lines.zIndex = 0;

      //  console.log( this.viewer.scene.primitives)
      // console.log( this.viewer.scene)
      //  console.log( this.viewer.scene.groundPrimitives)

      this.primitiveList.push(primitive);
    },
    // 第二次选择管线图层（显示）
    addTwiceLineEntity(res) {
      // console.log(res)
      // console.log(this.viewer.scene.groundPrimitives)

      this.viewer.scene.groundPrimitives._primitives.forEach((element) => {
        if (element.hasOwnProperty("id") && res.id == element.id) {
          element.show = true;
        }
      });
      // // console.log(res);
      // // console.log("第二次加载");
      // let that = this;
      // var attribute;
      // res.data.forEach((element) => {
      //   let colortype = element.properties.grade;
      //   var color;
      //   switch (colortype) {
      //     case "0":
      //       // 输水干管
      //       // color = "#00a9fd";
      //       color = [255, 122, 0];

      //       break;
      //     case "1":
      //       // 供水干管
      //       // color = "#6fe1f9";
      //       color = [0, 169, 253];

      //       break;
      //     case "2":
      //       // 分支管
      //       // color = "#ff7a00";
      //       color = [111, 225, 249];

      //       break;
      //     case "3":
      //       // 直分支管
      //       // color = "#fda75d";
      //       color = [111, 225, 249];

      //       break;
      //     case "4":
      //       // 支管
      //       // color = "#44ab4f";
      //       color = [68, 171, 79];

      //       break;
      //     case "5":
      //       // 分支管
      //       // color = "#80b4eb";
      //       color = [128, 180, 235];

      //       break;
      //   }
      //   let id = {
      //     UserID: element.properties.UserID,
      //   };
      //   // console.log(" this.primitiveList", this.primitiveList);
      //   this.primitiveList.forEach((e) => {
      //     // console.log(e);

      //     attribute = e.getGeometryInstanceAttributes(JSON.stringify(id));
      //     // console.log("attribute", attribute);
      //     if (attribute != undefined) {
      //       attribute.color = Cesium.ColorGeometryInstanceAttribute.toValue(
      //         new Cesium.Color.fromBytes(color[0], color[1], color[2], 255)
      //       );
      //     }
      //   });
      // });
    },
    // 根据load判断是第几次点击管线图层
    addLineEntity(res) {
      if (res.load) {
        this.addTwiceLineEntity(res);
      } else {
        this.addOnceLineEntity(res);
      }
    },
    // 隐藏所选的管线图层
    removeLineEntity(res) {
      this.viewer.scene.groundPrimitives._primitives.forEach((element) => {
        if (element.hasOwnProperty("id") && res.id == element.id) {
          element.show = false;
        }
      });
      // console.log(this.primitiveList);
      // console.log(data, "====================");

      // let that = this;
      // var attribute;
      // res.data.forEach((element) => {
      //   let colortype = element.properties.grade;
      //   var color;
      //   switch (colortype) {
      //     case "0":
      //       // 输水干管
      //       // color = "#00a9fd";
      //       color = [255, 122, 0];

      //       break;
      //     case "1":
      //       // 供水干管
      //       // color = "#6fe1f9";
      //       color = [0, 169, 253];

      //       break;
      //     case "2":
      //       // 分支管
      //       // color = "#ff7a00";
      //       color = [111, 225, 249];

      //       break;
      //     case "3":
      //       // 直分支管
      //       // color = "#fda75d";
      //       color = [111, 225, 249];

      //       break;
      //     case "4":
      //       // 支管
      //       // color = "#44ab4f";
      //       color = [68, 171, 79];

      //       break;
      //     case "5":
      //       // 分支管
      //       // color = "#80b4eb";
      //       color = [128, 180, 235];

      //       break;
      //   }
      //   let id = {
      //     UserID: element.properties.UserID,
      //   };
      //   this.primitiveList.forEach((e) => {
      //     attribute = e.getGeometryInstanceAttributes(JSON.stringify(id));
      //     // console.log(attribute, "attribute");
      //     if (attribute != undefined) {
      //       attribute.color = Cesium.ColorGeometryInstanceAttribute.toValue(
      //         new Cesium.Color.fromBytes(color[0], color[1], color[2], 0)
      //       );
      //     }
      //   });
      // });
    },
    // 选择管点图层显示
    addPointEntity(data) {
      // this.viewer.scene.requestRender();
      // console.log(this.viewer.dataSources);
      let datalist;
      this.viewer.dataSources._dataSources.forEach((element) => {
        if (element.id == "dataSource1") {
          // console.log(element)
          datalist = element._entityCollection._entities._array;
        }
      });

      data.forEach((element) => {
        let idData = {
          deviceId: element.properties.device_id,
        };
        datalist.forEach((e) => {
          if (JSON.stringify(idData) == e.id) {
            e.show = true;
          }
        });
      });
    },
    // 选择管点图层隐藏
    removePointEntity(data) {
      let datalist;
      this.viewer.dataSources._dataSources.forEach((element) => {
        if (element.id == "dataSource1") {
          // console.log(element)
          datalist = element._entityCollection._entities._array;
        }
      });
      // console.log(data, this.billboardCollection._billboards)
      data.forEach((element) => {
        let idData = {
          deviceId: element.properties.device_id,
        };
        datalist.forEach((e) => {
          if (JSON.stringify(idData) == e.id) {
            e.show = false;
          }
        });
      });
    },
    // 根据load1判断是第几次点击管线图层（管线对应的文字显示）
    addLabelEntity(res) {
      // console.log(res);
      if (res.load1) {
        this.addTwiceLabelEntity(res);
      } else {
        this.addOnceLabelEntity(res);
      }
    },
    // 第一次选择管线图层（添加管线对应的文字）
    addOnceLabelEntity(res) {
      var labels = this.viewer.scene.primitives.add(new Cesium.LabelCollection());
      labels.id = res.id;
      this.Thematiclayer.forEach((element) => {
        if (element.id == res.id) {
          element.load1 = true;
        }
      });

      // console.log(res);
      // console.log("第一次加载Label");
      var showrgb = true;
      res.data.forEach((e) => {
        var x = e.properties.X;
        var y = e.properties.Y;

        let colortype = e.properties.grade;
        var color;
        switch (colortype) {
          case "0":
            // 输水干管
            // color = "#00a9fd";
            color = [255, 122, 0];

            break;
          case "1":
            // 供水干管
            // color = "#6fe1f9";
            color = [0, 169, 253];

            break;
          case "2":
            // 分支管
            // color = "#ff7a00";
            color = [111, 225, 249];

            break;
          case "3":
            // 直分支管
            // color = "#fda75d";
            color = [111, 225, 249];

            break;
          case "4":
            // 支管
            // color = "#44ab4f";
            color = [68, 171, 79];

            break;
          case "5":
            // 分支管
            // color = "#80b4eb";
            color = [128, 180, 235];

            break;
        }
        let idData = e.properties.name;

        // let pos = e.geometry.coordinates[0].flat();

        labels.add({
          id: e.id,
          show: showrgb,
          position: Cesium.Cartesian3.fromDegrees(x, y),
          text: idData,
          fillColor: new Cesium.Color.fromBytes(255, 255, 255, 255),
          showBackground: true,
          backgroundColor: new Cesium.Color.fromBytes(color[0], color[1], color[2], 255),
          font: "12px Helvetica",
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.CENTER,
          scale: 1.0,
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 5000),
          // eyeOffset: Cesium.Cartesian3(200.0, 200.0, 0.0),
          // heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
        });
      });
      // console.log(this.viewer.scene.primitives);
    },
    // 第二次选择管线图层（显示管线对应的文字）
    addTwiceLabelEntity(res) {
      // console.log(res);
      // console.log("第二次加载Label");
      this.viewer.scene.primitives._primitives.forEach((element) => {
        if (element.hasOwnProperty("blendOption") && res.id == element.id) {
          element.show = true;
        }
      });
    },
    // 隐藏所选的管线图层对应的文字
    removeLabelEntity(res) {
      this.viewer.scene.primitives._primitives.forEach((element) => {
        if (element.hasOwnProperty("blendOption") && res.id == element.id) {
          element.show = false;
        }
      });
      // this.labels._labels.forEach((element, index) => {
      //   res.data.forEach((e) => {
      //     if (e.id == element._id) {
      //       // e._show=true
      //       const l = this.labels.get(index);
      //       l.show = false;
      //     }
      //   });
      // });
    },
    // 添加非管线和非管点图层（管线流向，行政区划，村名，村点位，矢量图层）
    addentity(layername) {
      let that = this;
      // console.log(layername, "layername");
      switch (layername) {
        case "ANDINGQU:gxlxlayer":
          if (that.addgxlx == false) {
            this.addAllLiuxiang();
            that.addgxlx = true;
          } else {
            that.showAllLiuxiang();
          }

          break;
        case "ANDINGQU:xzqhlayer":
          for (let index = 0; index < that.xzqhlayerdata.length; index++) {
            // console.log(data[0][i])
            var entity = that.viewer.entities.getById("xzqhlayers" + index);
            // console.log(entity)
            entity.show = true;
          }
          break;

        default:
          break;
      }
    },
    // 隐藏非管线和非管点图层（管线流向，行政区划，村名，村点位，矢量图层）
    removeentity(layername) {
      let that = this;
      switch (layername) {
        case "ANDINGQU:gxlxlayer":
          that.removeGuanlineliux();

          break;
        case "ANDINGQU:xzqhlayer":
          for (let index = 0; index < that.xzqhlayerdata.length; index++) {
            // console.log(data[0][i])
            var entity = that.viewer.entities.getById("xzqhlayers" + index);
            // console.log(entity)
            entity.show = false;
          }
          break;

        default:
          break;
      }
    },

    // 添加geoserver发布的图层（村名，村点位，行政区划）
    addgeoserver(layername) {
      let url = basegeoserver + "/geoserver/ANDINGQU/wms";
      let that = this;
      switch (layername) {
        case "ANDINGQU:wzbzlayer":
          if (!this.addcunming) {
            // addWMSLayer(that.viewer, "ANDINGQU:村名");
            addLayer(this.viewer, "WMS", "村名图层", "ANDINGQU:村名", url);
            this.addcunming = true;
          }

          // showOrhideWMSLayer(that.viewer, "ANDINGQU:村名", true);
          showLayer(that.viewer, "ANDINGQU:村名");
          break;
        case "ANDINGQU:dwbzlayer":
          if (!this.addcundian) {
            // addWMSLayer(that.viewer, "ANDINGQU:xzc");
            addLayer(this.viewer, "WMS", "村点位图层", "ANDINGQU:xzc", url);
            this.addcundian = true;
          }
          showLayer(that.viewer, "ANDINGQU:xzc");
          // showOrhideWMSLayer(that.viewer, "ANDINGQU:xzc", true);

          break;
        case "ANDINGQU:sltclayer":
          // showOrhideBaseLayer(that.viewer, "ANDINGQU:sltclayer", true);
          showLayer(that.viewer, "ANDINGQU:sltclayer");
          break;

        default:
          break;
      }
    },
    // 隐藏geoserver发布的图层（村名，村点位，行政区划）
    removegeoserver(layername) {
      let that = this;
      switch (layername) {
        case "ANDINGQU:wzbzlayer":
          // showOrhideWMSLayer(that.viewer, "ANDINGQU:村名", false);
          hideLayer(that.viewer, "ANDINGQU:村名");
          break;
        case "ANDINGQU:dwbzlayer":
          // showOrhideWMSLayer(that.viewer, "ANDINGQU:xzc", false);
          hideLayer(that.viewer, "ANDINGQU:xzc");
          break;
        case "ANDINGQU:sltclayer":
          // showOrhideBaseLayer(this.viewer, "ANDINGQU:sltclayer", false);
          hideLayer(that.viewer, "ANDINGQU:sltclayer");
          break;

        default:
          break;
      }
    },

    //  点击流向图层，选择显示管线对应的流向图层
    showLayerliuxiang(res) {
      if (!this.Thematiclayer[12].show) {
        return;
      }

      // console.log(res, "显示" + res.label + "流向");
      // console.log(this.Thematiclayer[12].show);
      this.viewer.scene.groundPrimitives._primitives.forEach((element) => {
        // console.log(element);
        if (
          element.hasOwnProperty("id") &&
          String(element.id).substring(10) == res.label
        ) {
          element.show = true;
          this.viewer.scene.groundPrimitives.raiseToTop(element);
          // this.viewer.scene.groundPrimitives._primitives.splice(index, 1);
        }
      });
    },
    // 点击流向图层，选择隐藏管线对应的流向图层
    hideLayerliuxiang(res) {
      if (!this.Thematiclayer[12].show) {
        return;
      }
      // console.log(res, "隐藏" + res.label + "流向");
      // console.log(this.Thematiclayer[12].show);
      this.viewer.scene.groundPrimitives._primitives.forEach((element) => {
        // console.log(element);
        if (
          element.hasOwnProperty("id") &&
          String(element.id).substring(10) == res.label
        ) {
          element.show = false;
          this.viewer.scene.groundPrimitives.raiseToTop(element);
          // this.viewer.scene.groundPrimitives._primitives.splice(index, 1);
        }
      });
    },
    // 添加流向图层
    addAllLiuxiang() {
      this.Thematiclayer.forEach((element) => {
        if (element.type == "line") {
          this.addOnceLayerLiuxiang(element);
        }
      });
      // this.labelslist.push(labels) ;
    },
    // 第一次添加流向图层
    addOnceLayerLiuxiang(res) {
      var guanxiandata = res.data;

      var instances = [];
      guanxiandata.forEach((e, index) => {
        let pos = e.geometry.coordinates[0].flat();
        instances.push(
          new Cesium.GeometryInstance({
            geometry: new Cesium.GroundPolylineGeometry({
              positions: Cesium.Cartesian3.fromDegreesArray(pos),
              // width: element.properties.lineWidth / 5
              width: 2,
            }),
          })
        );
      });
      let material1 = new Cesium.Material({
        fabric: {
          uniforms: {
            uTime: 2,
            length1: 1000,
            alpha: 0.7,
          },
          source: `
  czm_material czm_getMaterial(czm_materialInput materialInput)
  {
    // 生成默认的基础材质
    czm_material material = czm_getDefaultMaterial(materialInput);
    // material.diffuse = vec3(0.8470588235294118, 0.66666666, 0.8156862745098039);
    // 发光
    material.specular = 1.0;
    material.shininess = 0.8;
    // material.emission = vec3(0.0, 0.66666666, 0.0);
    material.alpha = alpha;
    // material.diffuse = vec3(materialInput.st+uTime, 0.5);
    float strength = mod((materialInput.s+uTime) * length1, 1.0);
    material.diffuse = vec3(0.0, strength,1.0);
    return material;
  }
`,
        },
      });

      // 使用gasp实现补间动画，完成动画效果
      gsap.to(material1.uniforms, {
        uTime: 1,
        duration: 1000,
        repeat: -1,
        ease: "linear",
      });
      var primitive = new Cesium.GroundPolylinePrimitive({
        geometryInstances: instances,
        appearance: new Cesium.EllipsoidSurfaceAppearance({
          material: material1,
        }),
      });

      // this.viewer.scene.groundPrimitives.add(primitive);
      var lines = this.viewer.scene.groundPrimitives.add(primitive);
      lines.id = "gxliuxiang" + res.label;
      lines.show = res.show;
      this.primitiveList.push(primitive);
    },
    // 显示管线对应的所有流向图层
    showAllLiuxiang() {
      // console.log(" 显示所有流向");
      this.viewer.scene.groundPrimitives._primitives.forEach((e) => {
        // console.log(e);
        for (let index = 0; index < this.Thematiclayer.length; index++) {
          // const element = array[index];
          if (
            this.Thematiclayer[index].label == String(e.id).substring(10) &&
            this.Thematiclayer[index].show == true
          ) {
            e.show = true;
          }
        }
      });
    },
    // 隐藏管线对应的所有流向图层
    removeGuanlineliux() {
      // console.log(
      //   this.viewer.scene.groundPrimitives._primitives,
      //   "this.viewer.scene.groundPrimitives._primitives"
      // );
      this.viewer.scene.groundPrimitives._primitives.forEach((element, index) => {
        if (
          element.hasOwnProperty("id") &&
          String(element.id).slice(0, 10) == "gxliuxiang"
        ) {
          element.show = false;
          // this.viewer.scene.groundPrimitives._primitives.splice(index, 1);
        }
      });
    },

    // 添加乡镇边界
    addxzqhlayer() {
      // console.log(this.viewer.imageryLayers);
      // console.log(this.xzqhlayerdata, "xzqhlayerdata");
      for (let i = 0; i < this.xzqhlayerdata.length; i++) {
        // console.log(data[0][i])
        this.viewer.entities.add({
          id: "xzqhlayers" + i,
          // show:false,
          polyline: {
            positions: Cesium.Cartesian3.fromDegreesArray(
              this.xzqhlayerdata[i].geometry.coordinates[0][0].flat()
            ),
            // clampToGround: true,//开启贴地
            // positions: Cesium.Cartesian3.fromDegreesArrayHeights(element.geometry.coordinates[0].flat()),
            width: 4,
            clampToGround: true, //开启贴地
            // material: Cesium.Color.fromCssColorString("#04DE51")
            material: new Cesium.PolylineOutlineMaterialProperty({
              color: Cesium.Color.WHITE,
              outlineWidth: 2,
              // outlineColor: Cesium.Color.BLUE,
              outlineColor: Cesium.Color.fromCssColorString("rgba(201, 233, 255, 0.1)"),
            }),
          },
        });
      }
    },
    // 放大
    zoomout(type) {
      let position = this.viewer.camera.position;
      let cameraHeight = this.viewer.scene.globe.ellipsoid.cartesianToCartographic(
        position
      ).height;
      // 每次缩小 20 倍，参数可改
      let moveRate = cameraHeight / 20;
      this.viewer.camera.moveForward(moveRate);
    },
    // 缩小
    zoomin(type) {
      let position = this.viewer.camera.position;
      let cameraHeight = this.viewer.scene.globe.ellipsoid.cartesianToCartographic(
        position
      ).height;
      // 每次缩小 20 倍，参数可改
      let moveRate = cameraHeight / 20;
      this.viewer.camera.moveBackward(moveRate);
    },
    //  回到初始位置
    gohome(type) {
      // console.log("gohome", type);
      switch (type) {
        case 3:
          cameraFlyto(this.viewer, [104.63125445585818, 34.8, 100000]);
          break;
        case 2:
          this.viewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(104.65, 35.64, 200000),
          });
          break;

        default:
          break;
      }
    },
    // 添加地图覆盖物点悬事件
    addMouseclickandhover() {
      let that = this;
      let viewer = this.viewer;
      // this.siteInfoDom = document.getElementById("info_box");
      // 取消鼠标双击事件
      viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
      );
      const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
      handler.setInputAction(async function (click) {
        const pickedFeature = viewer.scene.pick(click.position);

        if (Cesium.defined(pickedFeature)) {
          console.log(pickedFeature);
          // let parseid = JSON.parse(pickedFeature.id.id);
          // let id = pickedFeature.id.id;
          Bus.$emit("infowindowsIF", true);
          // console.log(pickedFeature, "pickedFeature");

          if (
            pickedFeature.hasOwnProperty("collection") &&
            pickedFeature.id.id.search("deviceId") >= 0
          ) {
            let parseid = JSON.parse(pickedFeature.id.id);
            // var id = pickedFeature.id.id;
            // console.log("阀门", parseid);
            // Bus.$emit("infodata", id);
            const res = await getBoxPointData(`device_id='${parseid.deviceId}'`);
            // console.log(res.features[0].properties.device_id, "图标点击之前")
            let idData = {
              deviceId: res.features[0].properties.device_id,
              sttp: res.features[0].properties.sttp,
              type: res.features[0].properties.TYPE,
              sp: res.features[0].properties.SP,
            };
            // that.infotype = "movement";
            let data = JSON.stringify(idData);

            Bus.$emit("infodata", data);
          } else if (
            typeof pickedFeature.id == "string" &&
            pickedFeature.id.search("UserID") >= 0
          ) {
            var id = pickedFeature.id;
            if (typeof id != "string") {
              return;
            }
            // console.log("管线", id);
            Bus.$emit("infodata", id);
            // ===================联通分析======================================================
            if (that.ltfx == true) {
              that.addlinesHeightColor(id);
              Bus.$emit("ltfxid", id);
            } else if (that.bgfx == true) {
              // ===================爆管分析======================================================
              that.addlinesHeightColor(id, true);
              Bus.$emit("bgfxid", id);
            } else if (that.zdmfx == true) {
              // ===================剖面分析======================================================
              that.addlinesHeightColor(id);
              Bus.$emit("zdmfxid", id);
            } else if (that.mapinit == true) {
              //设置工具栏弹框选项状态
              // that.addlinesHeightColor(id);
              that.colorheightone(id);
            }
          } else {
            // console.log("其他类型");
            Bus.$emit("dosetmethodes1", true);
          }
          // that.$store.commit("changemapstatus", true);
          // if (parseid.hasOwnProperty("UserID")) {
          //   // console.log("管线",pickedFeature.id.id)
          //   Bus.$emit("infodata", id);
          //   // ===================联通分析======================================================
          //   if (that.ltfx == true) {
          //     that.addlinesHeightColor(id);
          //     Bus.$emit("ltfxid", id);
          //   } else if (that.bgfx == true) {
          //     // ===================爆管分析======================================================
          //     that.addlinesHeightColor(id, true);
          //     Bus.$emit("bgfxid", id);
          //   } else if (that.zdmfx == true) {
          //     // ===================剖面分析======================================================
          //     that.addlinesHeightColor(id);
          //     Bus.$emit("zdmfxid", id);
          //   } else if (that.mapinit == true) {
          //     //设置工具栏弹框选项状态
          //     // that.addlinesHeightColor(id);

          //     that.colorheightone(id);
          //   }
          // } else if (parseid.hasOwnProperty("deviceId")) {
          // console.log("阀门",pickedFeature.id.id)
          // let ID = JSON.parse(pickedFeature.id.id);
          // const res = await getBoxPointData(
          //   `device_id='${parseid.deviceId}'`
          // );
          // // console.log(res.features[0].properties.device_id, "图标点击之前")
          // let idData = {
          //   deviceId: res.features[0].properties.device_id,
          //   sttp: res.features[0].properties.sttp,
          //   type: res.features[0].properties.TYPE,
          //   sp: res.features[0].properties.SP,
          // };
          // // that.infotype = "movement";
          // let data = JSON.stringify(idData);
          // Bus.$emit("infodata", data);
          // }
        } else {
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },

    // 高亮管线（id）
    addlinesHeightColor(id, type) {
      // console.log(id, "id");
      var that = this;
      this.Thematiclayer.forEach((element) => {
        if (element.type == "line" && element.show == true) {
          element.data.forEach((item) => {
            let idData = {
              UserID: item.properties.UserID,
            };
            if (JSON.stringify(idData) === id) {
              // console.log(id, "===================");
              that.addLinesInfoData(id, type);
              var attribute;
              if (type) {
                this.primitiveList.forEach((e) => {
                  attribute = e.getGeometryInstanceAttributes(id);
                  // console.log(attribute, e, "attribute");
                  if (attribute != undefined) {
                    attribute.color = Cesium.ColorGeometryInstanceAttribute.toValue(
                      Cesium.Color.fromRandom({
                        alpha: 0.0,
                      })
                      // Cesium.Color.RED
                      // Cesium.Color.fromCssColorString(color)
                    );
                  }
                });
              } else {
                this.primitiveList.forEach((e) => {
                  attribute = e.getGeometryInstanceAttributes(id);
                  // console.log(attribute, "attribute");
                  if (attribute != undefined) {
                    attribute.color = Cesium.ColorGeometryInstanceAttribute.toValue(
                      // Cesium.Color.fromRandom({
                      //   alpha: 1.0,
                      // })
                      Cesium.Color.BLUE
                      // Cesium.Color.fromCssColorString(color)
                    );
                  }
                });
              }
            } else {
              // console.log(id, "=====buxianshi==============");
            }
            // console.log(id)
          });
        }
      });
    },
    // 暂存高亮之后管线的信息（根据管线id）(方便清除)
    async addLinesInfoData(id, type) {
      // console.log(id)
      let ID = JSON.parse(id);
      const res = await getBoxLineData(`UserID='${ID.UserID}'`);
      // console.log(res, "res=============================");
      if (res.features[0] != []) {
        this.heightColorlinesList.push(res.features[0]);
        if (type) {
          this.addmaterialREDline();
        }
      }
    },
    addmaterialREDline() {
      var x = 1;
      var flog = true;
      var material = new Cesium.ColorMaterialProperty(
        new Cesium.CallbackProperty(function () {
          if (flog) {
            x = x - 0.01;
            if (x <= 0) {
              flog = false;
            }
          } else {
            x = x + 0.01;
            if (x >= 1) {
              flog = true;
            }
          }
          // console.log(x)
          return Cesium.Color.RED.withAlpha(x);
        }, false)
      );
      this.viewer.entities.add({
        name: "P",
        id: "materialREDline" + this.heightColorlinesList.length,
        polyline: {
          positions: Cesium.Cartesian3.fromDegreesArray(
            this.heightColorlinesList[
              this.heightColorlinesList.length - 1
            ].geometry.coordinates[0].flat()
          ),
          clampToGround: true, //开启贴地
          // positions: Cesium.Cartesian3.fromDegreesArrayHeights(element.geometry.coordinates[0].flat()),
          width: 6,
          // material: Cesium.Color.RED, //颜色
          material: material,
        },
      });
    },
    removematerialREDline() {
      this.heightColorlinesList.forEach((element, index) => {
        var entity = this.viewer.entities.getById("materialREDline" + (index + 1));
        // console.log("materialREDline" + index);
        this.viewer.entities.remove(entity);
      });
    },
    // 清除屏幕上高亮的线的数据================================
    clearHeightColoridlist() {
      // console.log(this.heightColorlinesList, "this.heightColorlinesList");
      this.clearHeightColor(this.heightColorlinesList);
    },
    clearHeightColor(data) {
      // console.log(data);
      data.forEach((element) => {
        let colortype = element.properties.grade;
        var color;
        var img;
        switch (colortype) {
          case "0":
            // 输水干管
            // color = "#00a9fd";
            color = [255, 122, 0];
            img = "./images/0000.png";

            break;
          case "1":
            // 供水干管
            // color = "#6fe1f9";
            color = [0, 169, 253];
            img = "./images/1111.png";

            break;
          case "2":
            // 分支管
            // color = "#ff7a00";
            color = [111, 225, 249];
            img = "./images/2222.png";

            break;
          case "3":
            // 直分支管
            // color = "#fda75d";
            color = [111, 225, 249];
            img = "./images/2222.png";

            break;
          case "4":
            // 支管
            // color = "#44ab4f";
            color = [68, 171, 79];
            img = "./images/4444.png";

            break;
          case "5":
            // 分支管
            // color = "#80b4eb";
            color = [128, 180, 235];
            img = "./images/5555.png";

            break;

          default:
            color = "#ffffff";
            break;
        }
        let id = { UserID: element.properties.UserID };
        // var entity = this.viewer.entities.getById(JSON.stringify(id));
        // // console.log(entity,"entity")
        // // this.viewer.entities.remove(entity);
        // entity.polyline.material = new Cesium.Color.fromBytes(
        //   color[0],
        //   color[1],
        //   color[2],
        //   255
        // );
        // entity.polylineVolume.material.url = img;
        var attribute;
        this.primitiveList.forEach((e) => {
          attribute = e.getGeometryInstanceAttributes(JSON.stringify(id));
          // console.log(attribute, "attribute");
          if (attribute != undefined) {
            attribute.color = Cesium.ColorGeometryInstanceAttribute.toValue(
              // Cesium.Color.fromRandom({
              //   alpha: 1.0,
              // })
              // Cesium.Color.RED
              new Cesium.Color.fromBytes(color[0], color[1], color[2], 255)
            );
          }
        });
      });
    },
    // 添加红色标点
    addnewpoint(id) {
      let datalist = this.viewer.dataSources._dataSources[0]._entityCollection._entities
        ._array;
      datalist.forEach((e) => {
        if (id == e.id) {
          this.addPointInfoData(id, e.show);
          // alert("数据找到了");
          // console.log(e,'数据找到了')
          e.show = true;
          e._billboard.image = require("@/assets/poi/gz.png");
        } else {
          // alert('数据找bu到了')
          return;
        }
      });
    },
    // 暂存高亮之后图标的信息（根据图标id）(方便清除)
    async addPointInfoData(id, type) {
      // console.log(id)
      let ID = JSON.parse(id);
      const res = await getBoxPointData(`device_id='${ID.deviceId}'`);

      // console.log(res, "res===============device_id==============")
      this.heightColorpointsList = res.features[0];

      this.heightColorpointsType = type;
    },
    //  清除屏幕上所有高亮的标点
    removenewpoint() {
      // console.log(this.heightColorpointsList,"this.heightColorpointsList")
      this.clearpointHeightColor(this.heightColorpointsList, this.heightColorpointsType);
      this.heightColorpointsList = null;
      this.heightColorpointsType = null;
    },
    // 清除屏幕上高亮的标点(还原屏幕上的点位)
    clearpointHeightColor(data, type) {
      if (!data) {
        return;
      }
      let imgtype = data.properties.sttp;
      var img;
      switch (imgtype) {
        case "0":
          // 管道分界监控点
          img = require("@/assets/poi/fjjcd.png");
          break;
        case "1":
          // 管道非分界监控点
          img = require("@/assets/poi/ffjjcd.png");
          break;
        case "2":
          // 蓄水池测控点
          img = require("@/assets/poi/xscjcd.png");
          break;
        case "3":
          // 泵站测控点
          img = require("@/assets/poi/bzjcd.png");
          break;
        case "4":
          img = require("@/assets/poi/sc.png");
          break;
        case "5":
          img = require("@/assets/poi/sfz.png");
          break;
      }
      let idData = {
        deviceId: data.properties.device_id,
      };
      let datalist = this.viewer.dataSources._dataSources[0]._entityCollection._entities
        ._array;

      datalist.forEach((e) => {
        if (JSON.stringify(idData) == e.id) {
          // alert('数据找到了')
          // console.log(e,'数据找到了')
          e.show = type;
          e._billboard.image = img;
        } else {
          return;
          // alert('数据找bu到了')
        }
      });
    },
    // 定位
    dingweiFly(data) {
      // console.log(data,this.btntype,"----2----")
      switch (this.btntype) {
        case "3":
          // alert(3)
          // cameraFlyto(this.viewer, [data[0] + 0.006, data[1] - 0.015, 2000]);
          // cameraFlyto(this.viewer, [data[0], data[1], 2000]);
          this.viewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(data[0], data[1], data[2] + 2000),
          });
          break;
        case "2":
          // alert(2)
          this.viewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(data[0], data[1], data[2]),
          });
          break;

        default:
          break;
      }
    },
    //  =====================================================测量================================================================================
    measurePolyLine(c, type) {
      let showlabel;
      if (type) {
        showlabel = false;
      } else {
        showlabel = true;
      }
      let measure = new Cesium.Measure(this.viewer);

      measure.drawLineMeasureGraphics({
        clampToGround: this.clampToGround,
        showlabel: showlabel,
        callback: (e) => {
          // console.log(e);
          if (showlabel == false) {
            this.getposition(e);
          }
        },
      });
    },
    measurePolygon(c, type) {
      let showlabel;
      if (type) {
        showlabel = false;
      } else {
        showlabel = true;
      }
      let measure = new Cesium.Measure(this.viewer);
      measure.drawAreaMeasureGraphics({
        clampToGround: this.clampToGround,
        showlabel: showlabel,
        callback: (e) => {
          // this.pos=e
          // console.log(e);
          // pos = e;
          // console.log(pos, "pos");
          // return pos;
          if (showlabel == false) {
            this.getposition(e);
          }
        },
      });
    },
    measureHeight() {
      let measure = new Cesium.Measure(this.viewer);
      // 三维量测
      measure.drawTrianglesMeasureGraphics({ callback: () => {} });
    },
    measureDestroy() {
      let arr = this.viewer.dataSources._dataSources;

      for (let index = 0; index < arr.length; index++) {
        // const element = array[index];
        if (arr[index]._name != "dataSource1") {
          this.viewer.dataSources.remove(arr[index]);
        }
      }
    },
    getposition(data) {
      Bus.$emit("positions", data);
      // console.log(data, "data");
    },

    //  =====================================================缓冲区================================================================================

    // 查找并添加有区域缓冲的线的缓冲区域
    async colorheightone(id) {
      this.clearHeightColoridlist();
      this.addlinesHeightColor(id);
      this.removeallyxqu();
      this.selectallyxqu1([id]);
    },

    // 二次修改影响区域
    selectallyxqu1(idlist) {
      let that = this;
      const yxquList = [];

      function createRecord(id) {
        return getBoxLineData(`UserID='${id}'`);
      }
      const arrays = [];
      idlist.forEach((element) => {
        // console.log(element);
        arrays.push(createRecord(JSON.parse(element).UserID));
      });

      // 当所有请求都成功完成时，responses 是一个包含所有响应的数组
      Promise.all(arrays)
        .then((responses) => {
          // console.log(responses);

          responses.forEach((element) => {
            if (element.features[0].properties.yxquID.split("、").length > 0) {
              element.features[0].properties.yxquID.split("、").forEach((e) => {
                yxquList.push(e);
              });
            } else {
              yxquList.push(element.features[0].properties.yxquID);
            }
            // yxquList.push(element.features[0].properties.yxquID.split("、"));
          });
          function unique(arr) {
            return Array.from(new Set(arr));
          }
          // console.log(yxquList);
          // console.log(unique(yxquList));

          let datalist = unique(yxquList);
          datalist = datalist.filter((item) => item != "");
          that.selectyxqu(datalist);
        })
        .catch((error) => {
          // 如果任何一个请求失败，将会进入这个 catch 块
          console.log(error);
        });
    },
    selectyxqu(list) {
      let that = this;
      // console.log(list);
      function createRecord(id) {
        return getYXQYidData(`id='${id}'`);
      }
      const arrays = [];
      list.forEach((element) => {
        // console.log(element);

        arrays.push(createRecord(element));
      });

      // 当所有请求都成功完成时，responses 是一个包含所有响应的数组
      Promise.all(arrays)
        .then((responses) => {
          // console.log(responses);

          responses.forEach((element, i) => {
            if (element.features.length != 0) {
              that.addyxqy(element, i);
              this.allyxqudata.push(i);
            }
          });
        })
        .catch((error) => {
          // 如果任何一个请求失败，将会进入这个 catch 块
          console.log(error);
        });
    },
    addyxqy(res, id) {
      var x = 1;
      var flog = true;
      let material2 = new Cesium.ColorMaterialProperty(
        new Cesium.CallbackProperty(function () {
          if (flog) {
            x = x - 0.01;
            if (x <= 0) {
              flog = false;
            }
          } else {
            x = x + 0.01;
            if (x >= 1) {
              flog = true;
            }
          }
          // console.log(x)
          return Cesium.Color.YELLOW.withAlpha(x);
        }, false)
      );
      let line = {
        name: "P",
        id: "hcqy" + id,
        polyline: {
          positions: Cesium.Cartesian3.fromDegreesArray(
            res.features[0].geometry.coordinates[0][0].flat()
          ),
          clampToGround: true, //开启贴地
          // positions: Cesium.Cartesian3.fromDegreesArrayHeights(element.geometry.coordinates[0].flat()),
          width: 2,
          // material: Cesium.Color.YELLOW, //颜色
          material: material2,
        },
        polygon: {
          hierarchy: Cesium.Cartesian3.fromDegreesArray(
            res.features[0].geometry.coordinates[0][0].flat()
          ),
          material: material2,
        },
      };
      this.viewer.entities.add(line);
    },
    //  查找添加所有的缓冲区
    async selectallyxqu(id, type) {
      let ID = JSON.parse(id);
      const res = await getBoxLineData(`UserID='${ID.UserID}'`);
      if (!res) {
        return;
      }
      // console.log(res);
      let yxquID = res.features[0].properties.yxquID;
      // console.log(yxquID);
      // console.log(yxquID.split("、"));
      var yxquIDlist = yxquID.split("、");

      yxquIDlist.forEach(async (element) => {
        // console.log(element)
        let id = element;
        const res1 = await getYXQYidData(`id='${id}'`);
        // console.log(res1, "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr");
        if (!res1) {
          return;
        }
        if (res1.features.length != 0) {
          // console.log(res1, "=======");
          this.allyxqudata.push(id);
          // this.allyxqudata.push({
          //   data:res1,
          //   id:id,
          //   type:type
          // });
          this.addqycxpoly(res1, id, type);
          // console.log(res1, id, type);
        }
      });

      // console.log(id)
    },
    // 添加区域缓冲区
    addqycxpoly(res1, id, type) {
      // this.removeallyxqu();
      var material1;
      var material2;

      if (type == true) {
        var x = 1;
        var flog = true;
        material1 = new Cesium.ColorMaterialProperty(
          new Cesium.CallbackProperty(function () {
            if (flog) {
              x = x - 0.01;
              if (x <= 0) {
                flog = false;
              }
            } else {
              x = x + 0.01;
              if (x >= 1) {
                flog = true;
              }
            }
            // console.log(x)
            return Cesium.Color.WHEAT.withAlpha(x);
          }, false)
        );
        material2 = new Cesium.ColorMaterialProperty(
          new Cesium.CallbackProperty(function () {
            if (flog) {
              x = x - 0.01;
              if (x <= 0) {
                flog = false;
              }
            } else {
              x = x + 0.01;
              if (x >= 1) {
                flog = true;
              }
            }
            // console.log(x)
            return Cesium.Color.YELLOW.withAlpha(x);
          }, false)
        );
      } else {
        material1 = Cesium.Color.WHEAT.withAlpha(0.2);
        material2 = Cesium.Color.YELLOW.withAlpha(1);
      }

      let line = {
        name: "P",
        id: "hcqy" + id,
        polyline: {
          positions: Cesium.Cartesian3.fromDegreesArray(
            res1.features[0].geometry.coordinates[0][0].flat()
          ),
          clampToGround: true, //开启贴地
          // positions: Cesium.Cartesian3.fromDegreesArrayHeights(element.geometry.coordinates[0].flat()),
          width: 2,
          // material: Cesium.Color.YELLOW, //颜色
          material: material2,
        },
        polygon: {
          hierarchy: Cesium.Cartesian3.fromDegreesArray(
            res1.features[0].geometry.coordinates[0][0].flat()
          ),
          material: material1,
        },
      };
      this.viewer.entities.add(line);
    },
    // 删除缓冲区的区域
    removeallyxqu() {
      this.allyxqudata.forEach((element) => {
        var entity = this.viewer.entities.getById("hcqy" + element);
        this.viewer.entities.remove(entity);
      });
    },
    drawPolygon(positions) {
      // console.log(positions)
      // this.positions = positions;
      let viewer = this.viewer;
      if (positions.length < 2) return;
      return viewer.entities.add({
        name: "",
        id: "mianjhdx",

        polygon: {
          clampToGround: true,
          // hierarchy: positions,
          // // eslint-disable-next-line new-cap
          // material: new Cesium.ColorMaterialProperty(
          //   Cesium.Color.WHEAT.withAlpha(0.4)
          // ),
          hierarchy: new Cesium.PolygonHierarchy(positions),
          material: Cesium.Color.RED.withAlpha(0.3),
          classificationType: Cesium.ClassificationType.BOTH,
        },
      });
    },
    removePolygon() {
      var entity = this.viewer.entities.getById("mianjhdx");
      this.viewer.entities.remove(entity);
    },
  },
};
</script>

<style lang="scss" scoped>
.map {
  width: 100%;
  height: 100%;
  // position: fixed;

  #cesiumContainer {
    width: 100%;
    height: 100%;
    z-index: 1;
    // background-repeat: no-repeat;
  }
}
</style>
